var count;
$(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    var Modal = $(".modal-msg");
    Modal.fadeOut(0);

    var loader = $('.loading');
    loader.fadeOut(0);
    count = 1;

    $('.get-entity-form').submit(function (event) {
        event.preventDefault();
        var tableName = $('.table-name').val();
        var partitionName = $('.partition-name').val();
        if (tableName != '' && partitionName != '') {
            getEntities(tableName, partitionName);
        } else {
            Modal.addClass("msg-error");
            Modal.removeClass("msg-success");
            Modal.removeClass("text-success");
            Modal.addClass("text-danger");
            Modal.html('<p>Table and Partition Key is required</p>').slideDown(500);
            Modal.delay(4000);
            Modal.slideUp(500);
        }
    });

    $('.form-edit-entity').submit(function (event) {
        event.preventDefault();
        editEntityProcess();
    });

});

/*
 Basic Operations for container
 */
function createTable() {
    $('#createTable').hide();
    var tableName = $(".table-name").val();
    $.ajax({
        method: 'POST',
        url: url + "/table/create",
        data: $('.form-create-table').serialize(),
        success: function (response) {
            var res = JSON.parse(response);
            var Modal = $(".modal-msg");
            if (res.statusCode == 200) {
                Modal.addClass("msg-success")
                Modal.addClass("text-success")
                Modal.html(res.table + ": Created Succesfully").slideDown(500);
                Modal.delay(3000);
                location.reload();
                Modal.slideUp(500);
            } else if (res.statusCode == 400) {
                Modal.addClass("msg-error")
                Modal.addClass("text-danger")
                Modal.html(res.errorMessage).slideDown(500);
                Modal.delay(4000);
                Modal.slideUp(500);
            }
        },
    });
}

//  This function adds the key value pair to the GUI for additional values
function addField() {
    $('.entity-form').append('<div class="form-group"><div class="row"><div class="col-md-2"><input type="text" name="key-' + count + '" placeholder="Key" class="form-control"></div><div class="col-md-6"><input type="text" name="value-' + count + '" placeholder="Value" class="form-control"></div><div></div>');
    count++;
}

// This function sends the ajax request to the server to store data
function createEntity() {
    var form = $('.entity-form');
    var tableName = $('.table-name').val();
    var partitionName = $('.partition-name').val();
    $.ajax({
        method: 'POST',
        url: url + "/entity/create/" + tableName + "/" + partitionName,
        data: form.serialize(),
        success: function (response) {
            var res = JSON.parse(response);
            var Modal = $(".modal-msg");
            if (res.statusCode == 200) {
                Modal.addClass("msg-success")
                Modal.removeClass('text-danger');
                Modal.addClass("text-success")
                Modal.html("The entity has been created in '" + tableName + "'").slideDown(500);
                Modal.delay(3000);
                Modal.slideUp(500);
            } else if (res.statusCode == 400) {
                Modal.addClass("msg-error")
                Modal.addClass("text-danger")
                Modal.html(res.errorMessage).slideDown(500);
                Modal.delay(4000);
                Modal.slideUp(500);
            }
        },
    });
}

// Get the results from the Azure
function getEntities(tableName, partitionName) {
    var loader = $('.loading');
    loader.fadeIn(300);
    $.ajax({
        method: 'POST',
        url: url + "/entity/get/" + tableName + "/" + partitionName,
        success: function (response) {
            var res = JSON.parse(response);
            var Modal = $(".modal-msg");
            if (res.statusCode == 200) {
                Modal.addClass("msg-success")
                Modal.addClass("text-success")
                loader.fadeOut(0);
                Modal.html("Results have been retrieved from Azure Storage Table").slideDown(500);
                $('.results').html(res.view);
                Modal.delay(3000);
                Modal.slideUp(500);
            } else if (res.statusCode == 400) {
                Modal.addClass("msg-error")
                Modal.addClass("text-danger")
                loader.fadeOut(0);
                Modal.html(res.errorMessage).slideDown(500);
                Modal.delay(4000);
                Modal.slideUp(500);
            }
        },
    });
}

function deleteEntity(id) {
    var partitionKey = $(".row-" + id).find('.partition-key').text();
    var rowKey = $(".row-" + id).find('.row-key').text();
    var table = $(".table-name").val();
    var loader = $('.loading');
    loader.fadeIn(300);
    console.log(partitionKey);
    $.ajax({
        method: 'POST',
        url: url + "/entity/delete/" + table + "/" + partitionKey + "/" + rowKey,
        success: function (response) {
            var res = JSON.parse(response);
            var Modal = $(".modal-msg");
            if (res.statusCode == 200) {
                Modal.addClass("msg-success")
                Modal.addClass("text-success")
                loader.fadeOut(0);
                Modal.html("Row has been deleted").slideDown(500);
                $('.results').html(res.view);
                Modal.delay(3000);
                Modal.slideUp(500);

                $('.results').html(res.view);
                getEntities(table, partitionKey);

            } else if (res.statusCode == 400) {
                Modal.addClass("msg-error")
                Modal.addClass("text-danger")
                loader.fadeOut(0);
                Modal.html(res.errorMessage).slideDown(500);
                Modal.delay(4000);
                Modal.slideUp(500);
            }
        }
    });

    getEntities(table, partitionKey);
}

function editEntity(id) {
    var rowKey = $(".row-" + id).find('.row-key').text();
    var partitionKey = $(".row-" + id).find('.partition-key').text();
    var tableName = $(".table-name").val();
    window.location.href = url + '/entity/edit/' + $.trim(tableName) + "/" + $.trim(partitionKey) + "/" + $.trim(rowKey);
}

function editEntityProcess() {
    var loader = $('.loading');
    loader.fadeIn(300);
    $.ajax({
        url: url + "/entity/edit/process",
        method: "POST",
        data: $(".form-edit-entity").serialize(),
        success: function (response) {
            var res = JSON.parse(response);
            var Modal = $(".modal-msg");
            if (res.statusCode == 200) {
                Modal.addClass("msg-success");
                Modal.addClass("text-success");
                loader.fadeOut(0);
                Modal.html("Entity has been updated").slideDown(500);
                $('.results').html(res.view);
                Modal.delay(3000);
                Modal.slideUp(500);

                $('.results').html(res.view);
                getEntities(table, partitionKey);

            } else if (res.statusCode == 400) {
                Modal.addClass("msg-error");
                Modal.addClass("text-danger");
                loader.fadeOut(0);
                Modal.html(res.errorMessage).slideDown(500);
                Modal.delay(4000);
                Modal.slideUp(500);
            }
        }
    });
}

